<?php

class Application_Model_OcenaMapper
{
    protected $_dbTable;

    public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable()
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_Ocena');
        }
        return $this->_dbTable;
    }

    public function save(Application_Model_Ocena $ocena)
    {
        $data = array(
            'opis' => $ocena->getOpis(),
            'ocena' => $ocena->getOcena(),
            'produkt_idprodukt' => $ocena->getIdProdukt(),
            'stranka_emso' => $ocena->getStrankaEmso()
        );

        $row = $this->fetchRow($this->getDbTable()->getAdapter()->quoteInto('id = ?', $ocena->getId()));

        try {
            if (isset($row['id']) && $row['id']) {
                $where = array('id = ?' => $row['id']);
                $this->getDbTable()->update($data, $where);
            } else {
                $this->getDbTable()->insert($data);
            }
        } catch (Exception $e) {
            echo "Error: ".$e->getMessage();
            die;
        }

    }

    public function find($id, Application_Model_Ocena &$ocena)
    {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return;
        }
        $row = $result->current();

        $ocena->setId($row->id)
            ->setIdProdukt($row->produkt_idprodukt)
            ->setOcena($row->ocena)
            ->setOpis($row->opis)
            ->setStrankaEmso($row->stranka_emso);

    }

    public function fetchRow($where) {
        return $this->getDbTable()->fetchRow($where);
    }


    public function fetchAll($where) {
        return $this->getDbTable()->fetchAll($where);
    }

    public function update($id, $polje, $vrednost) {
        $where = $this->getDbTable()->getAdapter()->quoteInto('id = ?', $id);
        $this->getDbTable()->update(array($polje => $vrednost), $where);
    }

}

